package com.share.common.utils;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.share.module.sys.user.entity.User;
import com.share.module.sys.user.service.UserService;
import com.stock.common.lang.StringUtils;
import com.stock.common.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Slf4j
public class TokenUtil {

    /**
     * 生成token
     *
     * @return
     */
    public static String genToken(String userId, String sign) {
        return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
    }

    public static User getUser() {
        String token = null;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getHeader("token");
            if (StringUtils.isNotBlank(token)) {
                token = request.getParameter("token");
            } else {
                log.error("获取当前登录的token失败， token: {}", token);
                return null;
            }

            String userId = JWT.decode(token).getAudience().get(0);
            UserService userService = SpringUtils.getBean(UserService.class);
            return userService.getById(Integer.valueOf(userId));
        } catch (JWTDecodeException e) {
            log.error("Jwt异常:{}-{}", token, e);
            return null;
        } catch (NumberFormatException e) {
            log.error("类型转换异常", e);
            return null;
        }

    }

}
